/*
 *	entrypoint.c 
 *	© 2009 Tom Booth
 *
 *	Entry point into the threading test harness
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#include "workmanager.h"


// local functions

void* thread_entrypoint(void) {
	int r;
	char *holdr;
	
	// work out whether this is going to give jobs or process
	r = (((double)rand()/(double)RAND_MAX) * 100);
	
	if (r<10) {
		dferrors_printdebug("Worker thread created\n");
		
		// we are a worker thread
		while (1) {
			while (!wm_item_avaliable()) { pthread_cond_wait(&wm_more_jobs, &wm_more_jobs_mutex); }
			
			holdr = wm_get_item();
			
			dferrors_printdebug("Thread [%lu] processed %s\n", pthread_self(),(char*)holdr);
			
			//sleep(3);
		}
	}
	else {
		dferrors_printdebug("Input thread created\n");
		
		// we are an input thread
		while (1) {
			dferrors_printdebug("Item added\n");
			
			wm_add_item("This is a thread message");
			
			sleep((((double)rand()/(double)RAND_MAX) * 10));
		}
	}
}

int main(int argc, char *argv[]) {
	
	int num_threads, i;
	pthread_t thread_handle;
	
	wm_init_manager();
	
	// get the number of threads to be tested
	printf("Please enter the number of threads to test: ");
	scanf("%d", &num_threads);
	
	for (i=0; i<num_threads; i++) {
		pthread_create(&thread_handle, NULL, thread_entrypoint, NULL);
	}
	
	sleep(120);
	
	scanf("%d", &i);
	
	wm_destroy_manager();
}




